package com.fesine.service;

import com.fesine.dao.UserRepository;
import com.fesine.entity.User;
import com.fesine.enums.ResultEnum;
import com.fesine.exception.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description: 用户service实现类
 * @author: Fesine
 * @createTime:2017/8/30 14:59
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/8/30 14:59
 */
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public List<User> findAll(){
        return userRepository.findAll();
    }

    /**
     * 无主键值，插入到库
     * @param user
     * @return
     */
    public User addUser(User user) {
        return userRepository.save(user);
    }

    /**
     * 根据主键值更新
     * @param user
     * @return
     */
    public User updateUser(User user) {
        return userRepository.save(user);
    }

    /**
     * 根据主键id查询用户信息
     * @param id
     * @return
     */
    public User findUser(Integer id) {
        return userRepository.findOne(id);
    }

    /**
     * 根据主键删除用户信息
     * @param id
     */
    public void deleteUser(Integer id) {
        userRepository.delete(id);
    }

    /**
     * 自定义查询方法，根据用户年龄查询
     * @param age
     * @return
     */
    public List<User> findUserByAge(Integer age) {
        return userRepository.findByAge(age);
    }

    public void getUserAge(Integer id) throws Exception{
        Integer age = userRepository.findOne(id).getAge();
        if (age < 10) {
            throw new UserException(ResultEnum.PRIMARY_SCHOOL);
        } else if (age < 18) {
            throw new UserException(ResultEnum.NOT_ADULT);
        }


    }


}
